package com.zx.flow.api.execute.common;

import com.zx.flow.api.dict.FlowDict.Event;
import com.zx.flow.api.execute.model.FlowContext;
import com.zx.flow.api.execute.model.FlowNode;
import com.zx.flow.api.execute.model.FlowOperator;
import com.zx.flow.api.listener.FlowEvent;
import com.zx.flow.api.listener.request.FlowContext4Listener;
import com.zx.flow.api.listener.request.FlowNode4Listener;
import com.zx.flow.api.listener.request.FlowOperator4Listener;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

public class Convert {

    public static FlowContext4Listener to(FlowContext a) {
        if (a == null) {
            return null;
        }
        FlowContext4Listener b = new FlowContext4Listener();
        BeanUtils.copyProperties(a, b, "status");
        b.setStatus(a.getStatus().getCode());
        return b;
    }

    public static FlowNode4Listener to(FlowNode a) {
        if (a == null) {
            return null;
        }
        FlowNode4Listener b = new FlowNode4Listener();
        BeanUtils.copyProperties(a, b, "status", "operators", "operator");
        b.setOperator(to(a.getOperator()));
        b.setStatus(a.getStatus().getCode());

        List<FlowOperator4Listener> operators = new ArrayList<>();
        if (!CollectionUtils.isEmpty(a.getOperators())) {
            for (FlowOperator operator : a.getOperators()) {
                operators.add(to(operator));
            }
        }
        b.setOperators(operators);
        return b;
    }

    public static FlowOperator4Listener to(FlowOperator a) {
        if (a == null) {
            return null;
        }
        FlowOperator4Listener b = new FlowOperator4Listener();
        BeanUtils.copyProperties(a, b);
        return b;
    }

    public static FlowEvent to(FlowContext flow, FlowNode node, Event event) {
        FlowEvent res = new FlowEvent();
        res.setFlowContext(to(flow));
        res.setFlowNode(to(node));
        res.setEventCode(event.getCode());
        return res;
    }
}
